import React from 'react'
import BaseComponent from 'basecomponent'
import icons from 'icons'
import Button from "button";
import './style.scss'
import AntTable from 'anttable'
import {Form, Menu} from 'antd';
import api from 'apis'
import store from 'store'
import Link from "react-router/es/Link";
import moment from 'moment'
import UploadMusicModal from 'uploadMusicModal'
import appConfig from 'config'
import auth from 'auth'
import Dropzone from 'react-dropzone';

const FormItem = Form.Item
const menuItem = {
  benke: 0,
  shuoshi: 1,
  zhuanke: 2
}

class College extends BaseComponent {
  constructor() {
    super(...arguments);
    const location = this.props.location;
    this.state = {
      collegeData: {
        Id: location.query ?  parseInt(location.query.Id) : -1,
        University:  {Id: location.state ? location.state.uid : -1},
        Name:'',
        Image: '',
        DetailHtml:'',
        Introduce:'',
        DetailFiles:'',
        Music:{},
        Timestamp:-1,
        TotalPlayTimes:0,
        TotalComment: -1,
        TotalDuration: -1,
      },
      from: location.state? location.state.from : '',
      musicData: [{
        Id: '-',
        Name: '添加',
        PlayTimes:'-',
        Duration:'-',
        updateTime:'-'
      }],
      showModal:false,
      menuCurrent: menuItem.benke.toString(),
      majorCurrentPage: 1,
      majorPageSize: 10,
      majorData: [],
      collegeLogoImg: {},
      collegeLogoPreview: {},
      showMajorModal:false
    }
    store.set('currentCId', location.query.Id ? location.query.Id : 1)
  }

  componentDidMount() {
    const {collegeData} = this.state
    this.setState({from:this.props.location.state.from})
    if (this.checkCollegeId(collegeData)) {
      this.getCollegeDetail(collegeData.Id)
    }
  }

  getCollegeDetail(cid) {
    const{menuCurrent,musicData}=this.state
    let id = cid ? cid : store.get('currentCId');
    this.CDetailRP && this.CDetailRP.request.abort();
    this.CDetailRP = api.university.getCollegeDetail(id);
    this.registerRequest(this.CDetailRP.request);
    this.CDetailRP.promise
      .then((res) => {
        let data = res.Data||[]
        this.setState({collegeData:data});
        this.getMajorList(data.Id,menuCurrent)
        if(data.Image){
          this.setState({collegeLogoImg: `${appConfig.apiHost}/File/?pid=${data.Image}&key=${auth.getFileToken()}`})
        }
        if(data.Music){
          musicData[0] = data.Music
          this.setState({musicData:musicData})
        }
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  getMajorList(cid,type) {
    let id = cid ? cid : store.get('currentCId');
    this.MListRP && this.MListRP.request.abort();
    this.MListRP = api.university.getMajorList(id,type,null);
    this.registerRequest(this.MListRP.request);
    this.MListRP.promise
      .then((res) => {
        res.Data&&this.setState({majorData:res.Data})
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  handleMusicView(musicView) {
    const {musicData,collegeData} = this.state
    musicData[0].Id = musicView.Id
    musicData[0].Name = musicView.Name
    musicData[0].updateTime = moment(new Date()).format('YYYY.MM.DD hh:mm')
    let reviseCollege = Object.assign({},collegeData,{Music:{Id:musicView.Id}})
    this.setState({musicData: musicData})
    this.RCollegeRp && this.RCollegeRp.request.abort();
    this.RCollegeRp = api.university.reviseCollege(collegeData.Id , reviseCollege);
    this.registerRequest(this.RCollegeRp.request);
    this.RCollegeRp.promise
      .then((res) => {
        res.Data&&this.setState({collegeData:res.Data})
      })
  }

  handleMajorMusicView(musicView) {
    const {reviseMajor} = this.state
    let reviseData = Object.assign({},reviseMajor,{Music:{Id:musicView.Id}})
    this.RMajorRp && this.RMajorRp.request.abort();
    this.RMajorRp = api.university.reviseMajor(reviseMajor.Id , reviseData);
    this.registerRequest(this.RMajorRp.request);
    this.RMajorRp.promise
      .then((res) => {
        this.getMajorList(this.state.collegeId, this.state.menuCurrent)
      })
      .catch((err)=> {
        alert(err.msg)
      })
  }

  handleMenuClick(e) {
    const {collegeData} = this.state
    if (this.checkCollegeId(collegeData)) {
      this.getMajorList(collegeData.Id,e.key);
    }
    this.setState({menuCurrent:e.key});
  }

  topMajor(text, record) {
    let majorData = {}
    if(record.Order && record.Order === 1){
      majorData = Object.assign({}, record, {Order: 0})
    }else{
      majorData = Object.assign({}, record, {Order: 1})
    }
    this.reviseMajorRP && this.reviseMajorRP.request.abort()
    this.reviseMajorRP = api.university.reviseMajor(majorData.Id, majorData)
    this.registerRequest(this.reviseMajorRP.request)
    this.reviseMajorRP.promise
      .then((res) => {
        alert('成功')
        this.getMajorList(this.state.collegeId, this.state.menuCurrent)
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  handleSubmit(e) {
    e.preventDefault();
    const {collegeData} = this.state;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        collegeData.Name = values.Name;
        collegeData.Introduce = values.Introduce;
        if (this.checkCollegeId(collegeData)){
          this.reviseCollegeRP && this.reviseCollegeRP.request.abort();
          this.reviseCollegeRP = api.university.reviseCollege(collegeData.Id, collegeData);
          this.registerRequest(this.reviseCollegeRP.request);
          this.reviseCollegeRP.promise
            .then((res) => {
              res.Data && this.setState({collegeData: res.Data});
              if(res.State === 0) {
                alert('修改成功')
              }else{
                alert('错误：'+ res.State)
              }
            })
            .catch((err) => {
              alert(`错误：${err.statusCode}`)
            })
        } else {
          if(!(collegeData.University.Id === -1 || typeof collegeData.University.Id === 'undefined')){
            delete collegeData.Id
            this.addCollegeRP && this.addCollegeRP.request.abort();
            this.addCollegeRP = api.university.addCollege(collegeData);
            this.registerRequest(this.addCollegeRP.request);
            this.addCollegeRP.promise
              .then((res) => {
                res.Data && this.setState({collegeData: res.Data});
                if(res.State === 0) {
                  alert('修改成功')
                }else{
                  alert('错误：'+ res.State)
                }
              })
              .catch((err) => {
                alert(`错误：${err.statusCode}`)
              })
          }
          else{
            alert('添加学院出错')
          }
        }
      }
    });
  }

  handleLogoFileSelect(files) {
    const {collegeData} = this.state
    let file = files[0];
    if (file) {
      this.uploadLogoRP && this.uploadLogoRP.request.abort();
      this.uploadLogoRP = api.file.uploadFile(file);
      this.registerRequest(this.uploadLogoRP.request);
      this.uploadLogoRP.promise
        .then((res) => {
          this.setState({
            collegeLogoImg: res.Data || '', collegeData: Object.assign({},
              collegeData, {Image: res.Data || ''})
          });
        })
        .catch((err) => {
          alert(err.msg)
        })
    }
  }

  getLogoImgDiv() {
    const {collegeLogoImg, collegeLogoPreview} = this.state
    if (collegeLogoPreview.length > 0) {
      return <img className={'preview-img'} src={collegeLogoPreview}/>
    } else {
      if (collegeLogoImg.length > 0) {
        return <img className={'preview-img'}
                    src={`${appConfig.apiHost}/File/?pid=${collegeLogoImg}&key=${auth.getFileToken()}`}/>
      } else {
        return <div className={'default-wrapper'}>
          <img className={'image-default'} src={icons.uploadImg}/>
          <span>点击添加LOGO</span>
        </div>
      }
    }
  }

  checkCollegeId(collegeData){
    return !(collegeData.Id === -1 || collegeData.Id === '-1' || typeof collegeData.Id === 'undefined')
  }

  render() {
    const {getFieldDecorator, getFieldsError, getFieldError, isFieldTouched} = this.props.form;
    const {from, menuCurrent, page, majorCurrentPage, majorPageSize, majorData, collegeData,showModal,musicData, showMajorModal} = this.state;
    const voiceColumns = [{
      title: '编号',
      dataIndex: 'Id',
      key: 'Id',
    }, {
      title: '音频名称',
      dataIndex: 'Name',
      key: 'Name',
    }, {
      title: '播放量',
      dataIndex: 'PlayTimes',
      key: 'PlayTimes',
    }, {
      title: '时长',
      dataIndex: 'Duration',
      key: 'Duration',
    }, {
      title: '上传时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
    },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
             <a onClick={() => {
               this.setState({showModal:true})
             }}>上传</a>
            <span className="ant-divider"/>
          <a onClick={() => {
          }}>下载</a>
              <span className="ant-divider"/>
          <a onClick={() => {
          }}>删除</a>
        </span>
        ),
      }
    ];

    const majorColumns = [{
      title: '编号',
      dataIndex: 'Id',
      key: 'Id',
    }, {
      title: '专业名称',
      dataIndex: 'Name',
      key: 'Name',
      render: (text, record) => (
        <Link to={{pathname: '/home/revise/major', query: {Id: record.Id}, state: {revise: true}}}>{text}</Link>
      )
    }, {
      title: '播放量',
      dataIndex: 'totalPlay',
      key: 'totalPlay',
    }, {
      title: '时长',
      dataIndex: 'totalTime',
      key: 'totalTime',
    }, {
      title: '上传时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
    },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
            <a onClick={() => {
              this.topMajor(text, record)
              }}>{record.Order && record.Order === 1 ? '取消置顶' : '置顶'}</a>
            <span className="ant-divider"/>
             <a onClick={() => {
               this.setState({showMajorModal: true, reviseMajor: record})
             }}>上传</a>
            <span className="ant-divider"/>
          <a href={`${appConfig.apiHost}/File/?pid=${text.Url}&key=${auth.getFileToken()}`}
             download={`${text.Name}.mp3`}>
            下载
          </a>
        </span>
        ),
      }
    ];

    const voiceRowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
      }),
    };
    const majorRowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
      }),
    };
    return (
        <div className={'sem-main-content'}>
          <div className={'college-button-wrapper'}>
            <Button className={'back-button'} onClick={() => {
              if(from === '' || typeof from === 'undefined'){
                this.props.router.replace({pathname:'/home/add/university',query:{Id:collegeData.University.Id}})
              }else{
                this.props.router.goBack()
              }
            }}>{Button.AddOn({
              src: icons.backIcon, style: {
                width: '1rem',
                height: '1rem',
                display: 'block',
                backgroundRepeat: 'no-repeat',
              }
            })}</Button>
            <div className={'add-name'}>
              添加学院
            </div>
          </div>
          <Form onSubmit={this.handleSubmit.bind(this)} hideRequiredMark={true}>
            <div className={'college-top-div'}>
              <Dropzone className={'image-drop-zone'}
                        action={'http://101.201.51.208:9528/File'}
                        onDrop={this.handleLogoFileSelect.bind(this)}
                        accept={'image/*'}
                        multiple={false}>
                <div className={'default-wrapper'}>
                  {this.getLogoImgDiv()}
                </div>
              </Dropzone>
              <div className={'option-wrapper'}>
                <div className={'option-title'}>学院名称</div>
                <FormItem>
                  {getFieldDecorator('Name',{initialValue:collegeData.Name})(
                    <input className={'option-input'} type={'text'}/>
                  )}
                </FormItem>
              </div>
            </div>
            <div className={'college-middle-div'}>
              <div className={'title-wrapper'}>
                <span className={'title-bar'}/>
                <span className={'title-text'}>学院简介</span>
                <Button className={'title-btn-save'} onClick={() => {
                }}>保存</Button>
              </div>
              <FormItem>
                {getFieldDecorator('Introduce',{initialValue:collegeData.Introduce})(
                  <textarea className={'work-intro'}/>
                )}
              </FormItem>
            </div>
          </Form>

          <div className={'college-middle-div voice'}>
            <div className={'title-wrapper'}>
              <span className={'title-bar'}/>
              <span className={'title-text'}>部门音频</span>
            </div>
            <AntTable columns={voiceColumns} data={musicData} rowSelection={voiceRowSelection} pagenation={false}/>
          </div>

          <div className={'college-middle-div major'}>
            <div className={'title-wrapper'}>
              <Menu
                onClick={this.handleMenuClick.bind(this)}
                selectedKeys={[menuCurrent]}
                mode="horizontal"
              >
                <Menu.Item key={menuItem.benke}>
                  <span>本科专业</span>
                </Menu.Item>
                <Menu.Item key={menuItem.shuoshi}>
                  <span>硕士专业</span>
                </Menu.Item>
                <Menu.Item key={menuItem.zhuanke}>
                  <span>专科专业</span>
                </Menu.Item>
              </Menu>
              <Button className={'title-btn-more'} onClick={() => {
                if (this.checkCollegeId(collegeData)){
                  this.props.router.replace({pathname:'/home/add/major',query:{Id:-1},state:{
                    uid:collegeData.University.Id,
                    cid:collegeData.Id,
                    category: parseInt(menuCurrent)
                  }})
                }else {
                  alert('请先添加学院')
                }
              }}>添加</Button>
              <Button className={'title-btn-save'} onClick={() => {
              }}>保存</Button>
            </div>
            <AntTable columns={majorColumns} data={majorData} rowSelection={majorRowSelection}
                      pagination={true} currentPage={majorCurrentPage} pageSize={majorPageSize}
                      onChange={(pagination) => {
                        this.setState({
                          majorCurrentPage: pagination.current,
                          majorPageSize: pagination.pageSize,
                        })
                      }}/>
          </div>
          {showModal && <UploadMusicModal handleSave={(musicView)=>{this.handleMusicView(musicView)}}
                                          hideModal={()=>{this.setState({showModal:false})}}/>}
          {showMajorModal && <UploadMusicModal handleSave={this.handleMajorMusicView.bind(this)}
                                               hideModal={()=>{this.setState({showMajorModal:false})}}
          />}
        </div>
    );
  }
}

module.exports = Form.create()(College);
